package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Objects;

@Slf4j
@Component
public class MyInterceptor extends EmptyInterceptor{

    private static ThreadLocal<Cached> threadLocal = new ThreadLocal<Cached>();

    @Override
    public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        System.out.println("onLoad: " + entity.getClass());
        threadLocal.set(new Cached(entity.getClass(),id,entity));
        return super.onLoad(entity, id, state, propertyNames, types);
    }

    @Override
    public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
        threadLocal.set(new Cached(entity.getClass(),id,entity));
        return super.onSave(entity, id, state, propertyNames, types);
    }

    @Override
    public Object getEntity(String entityName, Serializable id) {
        return super.getEntity(entityName, id);
    }

    @Override
    public String onPrepareStatement(String sql) {
        log.info("onPrepareStatement");
        System.out.println("sql:" + sql);
        Cached id = threadLocal.get();
        threadLocal.remove();
        if(id == null) {
            return sql;
        }
//        if(id.clazz == UserR.class) {
//            System.out.println("id:" + id.id);
//            System.out.println("class:" + id.clazz);
//            UserR userR = (UserR) id.o;
//            System.out.println("entity:" + userR.getUserName());
//            return sql.replace("user_r_1", "user_r_1");
//        }
        return sql;
    }

    static class Cached {
        Class<?> clazz;
        Serializable id;
        Object o;
        Cached(Class<?> clazz, Serializable id, Object o) {
            super();
            this.clazz = clazz;
            this.id = id;
            this.o = o;
        }
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Cached cached = (Cached) o;
            return Objects.equals(clazz, cached.clazz) &&
                    Objects.equals(id, cached.id);
        }
        @Override
        public int hashCode() {
            return Objects.hash(clazz, id);
        }
    }


}
